<?php

namespace CHOMP\SGIBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class UsuarioType extends AbstractType
{
    private $id;
	private $esAdmin;
    
    public function __construct($id, $esAdmin){
        $this->id = $id;
		$this->esAdmin = $esAdmin;
    }    


    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('login')
            ->add('nombre')
            ->add('apellido')
            ->add('email')
			->add('telefono')
            ->add('estado', 'choice', array(
                'choices' => array(
                    0 => 'Activo',
					1 => 'Inactivo',
					2 => 'Lockeado'
		   		)));
			
			if($this->esAdmin == 'SI'){
				$builder->add('empresa', 'entity', array(
						 'class'=>'CHOMPSGIBundle:Empresa',
						 'property'=>'nombre',
						 'query_builder' => function (\CHOMP\SGIBundle\Entity\EmpresaRepository $repository)
						 {
							 return $repository->createQueryBuilder('u')
									->where('u.borrado = 0');
						 }
						));			
			}else{
				$builder->add('empresa', 'entity', array(
						 'class'=>'CHOMPSGIBundle:Empresa',
						 'property'=>'nombre',
						 'query_builder' => function (\CHOMP\SGIBundle\Entity\EmpresaRepository $repository)
						 {
							 return $repository->createQueryBuilder('u')
									->where('u.id = ?1')
									->setParameter(1, $this->id);
						 }
						));			
			}
			$builder->add('rol', 'entity', array(
					 'class'=>'CHOMPSGIBundle:Rol',
					 'property'=>'nombre',
					 'query_builder' => function (\CHOMP\SGIBundle\Entity\RolRepository $repository)
					 {
						 return $repository->createQueryBuilder('u')
								->where('u.empresa = '.$this->id.' and u.nombre != ?1')
								->setParameter(1, 'Administrador Root');
					 }
					));
    }
    
    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'CHOMP\SGIBundle\Entity\Usuario'
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'chomp_sgibundle_usuario';
    }
}
